package xyz.zhouxf.rpc.serializer.impl;

import com.caucho.hessian.io.*;
import xyz.zhouxf.rpc.enumeration.SerializerCode;
import xyz.zhouxf.rpc.serializer.RpcSerializer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author zhouxf
 * @date 2022/8/20
 */
public class HessianSerializer implements RpcSerializer {

    @Override
    public <T> byte[] serialize(T object) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        HessianOutput hessianOutput = new HessianOutput(byteArrayOutputStream);
        try {
            hessianOutput.writeObject(object);
            return byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                hessianOutput.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> type) {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
        HessianInput hessianInput = new HessianInput(byteArrayInputStream);
        try {
            return (T) hessianInput.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            hessianInput.close();
        }
        return null;
    }

    @Override
    public byte getCode() {
        return SerializerCode.HESSIAN.getCode();
    }
}
